package pluginGenerator;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;

import ctxSemanticsGen.Constants;


/**
 * 
 * 
 * 
 * @author guido
 *
 */
/* 
 * TODO: take a ResourceLoader from the source of the Velocity project
 * and check if this implementation is ok. (despite it works, but that's 
 * trial and error...)
 */ 
public class PluginResourceLoader extends ResourceLoader{

	
	@Override
	public long getLastModified(Resource arg0) {
		return 0;
	}

	
	@Override
	public InputStream getResourceStream(String templateName)
			throws ResourceNotFoundException {
		
		// TODO: works, but not sure it's ok.
		if (templateName.equals("VM_global_library.vm")){
			return null;
		}	
		
		
		/* Return value */
		InputStream is = null;

		try {
			
			Bundle b = Platform.getBundle(PluginConstants.PLUGIN_NAME); 
			URL url = b.getEntry(Constants.TEMPLATES_DIR + 
					             Constants.FILE_SEPARATOR +
					             templateName);
			
			is =  url.openStream();

		} catch (IOException e) { throw new RuntimeException(e); }

		return is;
		
	}

	
	@Override
	public void init(ExtendedProperties arg0) { }

	
	@Override
	public boolean isSourceModified(Resource arg0) {
		return false;
	}

}
